package com.xy.img;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.NinePatchDrawable;
import android.os.Environment;

import com.bumptech.glide.load.resource.bitmap.GlideBitmapDrawable;
import com.xy.FileUtil;
import com.xy.debug.LogUtils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by John on 2016/11/24.
 */

public class BitmapUtil {

    public static Bitmap drawable2Bmp(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
            return bitmapDrawable.getBitmap();
        } else if (drawable instanceof GlideBitmapDrawable) {
            GlideBitmapDrawable bitmapDrawable = (GlideBitmapDrawable) drawable;
            return bitmapDrawable.getBitmap();
        } else if (drawable instanceof NinePatchDrawable) {
            Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()
                    , drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
            Canvas canvas = new Canvas(bitmap);
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
            drawable.draw(canvas);
            return bitmap;
        }
        return null;
    }

    public static boolean saveBitmap(Bitmap bitmap, String srcPath) {
        File dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"xyapp");
        if (dir == null) {
            dir = new File(Environment.getExternalStorageDirectory(),"xyapp");
        }
        dir = FileUtil.checkFile(dir);
        return saveBitmap(bitmap, new File(dir, srcPath), 100, Bitmap.CompressFormat.JPEG);
    }

    public static boolean saveBitmap(Bitmap bitmap, File file, int quality, Bitmap.CompressFormat compressFormat) {
        BufferedOutputStream out = null;
        try {
            LogUtils.i(file.getAbsolutePath());
            if (file.exists()) {
                file.delete();
            }
            out = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(compressFormat, quality, out);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return true;
    }
}
